import hashlib
import json
from typing import Dict, Any

class ComHelper:
    """
    帮助类，提供签名生成等功能
    """
    
    @staticmethod
    def get_signature(payload: Dict[str, Any], key: str) -> str:
        """
        生成MD5签名
        
        Args:
            payload: 请求参数字典
            key: 密钥
            
        Returns:
            生成的签名字符串
        """
        # 参数排序
        filtered_keys = [k for k in payload.keys() if k not in [
            'PhoneNumberSet', 'SessionContext', 'SessionContextSet', 
            'ContextParamSet', 'TemplateParamSet', 'Signature', 
            'PhoneList', 'phoneSet'
        ]]
        
        # 按字典序排序
        sorted_keys = sorted(filtered_keys)
        
        # 拼接字符串
        sign_str = ''
        for k in sorted_keys:
            sign_str += f"{k}={payload[k]}&"
        
        # 结尾添加key
        sign_str += f"key={key}"
        
        # MD5加密并大写
        md5 = hashlib.md5()
        md5.update(sign_str.encode('utf-8'))
        signature = md5.hexdigest().upper()
        
        return signature